/*
Copyright 2011 Raymond Giorgi

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */

package edu.pitt.cs3530.identifier;

import java.io.Serializable;

import edu.pitt.cs3530.SystemInfo;
import edu.pitt.cs3530.applicationcontrolling.Machine;

/**
 * This class is sent from the application server to the front end. It
 * identifies itself using hostname and mac address and gives information about
 * its available frequencies
 */
public class HandshakeInfo implements Serializable, Cloneable {
	public static HandshakeInfo instance;

	private String macAddress;
	private String hostname;
	private Machine freqs;
	private HandshakeInfo child;
	private boolean isDatabase = false;

	/**
	 * Create and populate the handshake object
	 * 
	 * @return the handshake object
	 */
	public static HandshakeInfo createHandshake() {
		if (instance == null) {
			instance = new HandshakeInfo();
			instance.freqs = Machine.createFrequencies();
			instance.macAddress = SystemInfo.findMacAddress();
			instance.hostname = SystemInfo.findHostname();
			instance.freqs.printLocalFrequencies(System.out);
			System.out.println(instance.freqs.getTotalFrequency());
		}
		return instance;
	}

	public static HandshakeInfo createDatabaseHandshake() {
		if (instance == null) {
			createHandshake();
		}
		instance.isDatabase = true;
		return instance;
	}

	public static HandshakeInfo createHandshakeWChild(HandshakeInfo child) {
		HandshakeInfo info = createHandshake();
		info.child = child;
		return info;
	}

	private HandshakeInfo() {
	}

	public String getMacAddress() {
		return macAddress;
	}

	public String getHostname() {
		return hostname;
	}

	public Machine getFreqs() {
		return freqs;
	}

	public boolean isDatabase() {
		return isDatabase;
	}

	public HandshakeInfo getChild() {
		return child;
	}

	@Override
	public HandshakeInfo clone() {
		if (instance == null) {
			createHandshake();
		}
		HandshakeInfo retval = new HandshakeInfo();
		retval.freqs = instance.freqs;
		retval.hostname = instance.hostname;
		retval.macAddress = instance.macAddress;
		retval.isDatabase = instance.isDatabase;
		return retval;
	}
}
